package com.csp.resulthandle;

import com.alibaba.fastjson.JSONObject;
import com.csp.anotation.mng.MethodMapping;
import com.csp.session.ExecuteMsg;
import com.csp.session.impl.ResourceWrap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author:chengsp
 * @createTime:2019/8/23 10:29
 */
public class ListHandle implements ResultHandle {
    private final static ResultHandle resultHandle = new ListHandle();

    private ListHandle() {
    }

    public static ResultHandle getInstance() {
        return resultHandle;
    }

    private final static Logger logger = LoggerFactory.getLogger(ListHandle.class);

    @Override
    public Object execute(PreparedStatement statement, ExecuteMsg executeMsg, ResourceWrap resourceWrap) {
        try {
            resourceWrap.addStatement(statement);
            MethodMapping methodMapping = executeMsg.getMethodMapping();
            logger.info("预编译sql:{}", methodMapping.getPreparedSql());
            executeMsg.setParams(statement);
            ResultSet resultSet = statement.executeQuery();
            ResultSetMetaData metaData = resultSet.getMetaData();
            int columnCount = metaData.getColumnCount();
            String[] columnNames = new String[columnCount];
            for (int i = 0; i < columnCount; i++) {
                columnNames[i] = metaData.getColumnName(i + 1);
            }
            resourceWrap.addResultSet(resultSet);
            List resultList = new ArrayList<>();
            Class type = methodMapping.getReturnGenericType();
            while (resultSet.next()) {
                JSONObject object = new JSONObject();
                for (String columnName : columnNames) {
                    Object columnValue = resultSet.getObject(columnName);
                    object.put(columnName, columnValue);
                }
                resultList.add(object.toJavaObject(type));
            }
            return resultList;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
}
